#include "barchartwidget.h"
#include <QPainter>
#include <QPen>
#include <QFont>
#include <QFontMetrics>
#include <algorithm>
#include <cmath>

BarChartWidget::BarChartWidget(QWidget *parent)
    : QWidget(parent)
    , m_showValues(true)
    , m_leftMargin(30)
    , m_rightMargin(10)
    , m_topMargin(40)
    , m_bottomMargin(30)
    , m_barSpacing(10)
    , m_barWidth(20)
{
    // 初始化默认报警等级名称
    m_levelNames = {
        "Level 0", "Level 1", "Level 2", "Level 3", "Level 4",
        "Level 5", "Level 6", "Level 7", "Level 8", "Level 9"
    };

    // 初始化默认颜色（从绿色到红色的渐变）
    m_barColors = {
        QColor(0, 255, 0),     // 绿色 - 等级0
        QColor(85, 255, 0),    // 黄绿色
        QColor(170, 255, 0),   // 黄绿色
        QColor(255, 255, 0),   // 黄色
        QColor(255, 170, 0),   // 橙黄色
        QColor(255, 85, 0),    // 橙色
        QColor(255, 42, 0),    // 橙红色
        QColor(255, 21, 0),    // 红色
        QColor(200, 0, 0),     // 深红色
        QColor(150, 0, 0)      // 暗红色 - 等级9
    };

    // 初始化数据为0
    m_alarmCounts = QVector<int>(10, 0);

    setMaximumSize(400, 250);
}

void BarChartWidget::setAlarmData(const QVector<int> &alarmCounts)
{
    if (alarmCounts.size() != 10) {
        qWarning("Alarm data must contain exactly 10 elements");
        return;
    }

    m_alarmCounts = alarmCounts;
    update();
}

QVector<int> BarChartWidget::getAlarmData() const
{
    return m_alarmCounts;
}

void BarChartWidget::setAlarmLevelNames(const QVector<QString> &names)
{
    if (names.size() != 10) {
        qWarning("Level names must contain exactly 10 elements");
        return;
    }

    m_levelNames = names;
    update();
}

void BarChartWidget::setBarColors(const QVector<QColor> &colors)
{
    if (colors.size() != 10) {
        qWarning("Colors must contain exactly 10 elements");
        return;
    }

    m_barColors = colors;
    update();
}

void BarChartWidget::setTitle(const QString &title)
{
    m_title = title;
    update();
}

void BarChartWidget::setShowValues(bool show)
{
    m_showValues = show;
    update();
}

void BarChartWidget::clearData()
{
    m_alarmCounts.fill(0);
    update();
}

void BarChartWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 设置背景
    //painter.fillRect(rect(), QColor(240, 240, 240));

    // 绘制标题
    drawTitle(painter);

    // 绘制坐标轴
    drawAxes(painter);

    // 绘制柱状图
    drawBars(painter);

    // 绘制标签
    drawLabels(painter);
}

void BarChartWidget::drawTitle(QPainter &painter)
{
    if (m_title.isEmpty())
        return;

    painter.save();

    QFont font = painter.font();
    font.setPointSize(12);
    font.setBold(true);
    painter.setFont(font);
    painter.setPen(Qt::black);

    QRect titleRect(0, 10, width(), 15);
    painter.drawText(titleRect, Qt::AlignCenter, m_title);

    painter.restore();
}

void BarChartWidget::drawAxes(QPainter &painter)
{
    painter.save();

    QPen pen(Qt::black);
    pen.setWidth(1);
    painter.setPen(pen);

    // 绘制Y轴
    int chartBottom = height() - m_bottomMargin;
    int chartTop = m_topMargin;
    painter.drawLine(m_leftMargin, chartBottom, m_leftMargin, chartTop);

    // 绘制X轴
    painter.drawLine(m_leftMargin, chartBottom, width() - m_rightMargin, chartBottom);

    // 绘制Y轴刻度
    int maxValue = getMaxValue();
    if (maxValue == 0) maxValue = 1; // 避免除零

    int numTicks = 5;
    for (int i = 0; i <= numTicks; i++) {
        int value = i * maxValue / numTicks;
        int y = chartBottom - (chartBottom - chartTop) * i / numTicks;

        // 绘制刻度线
        painter.drawLine(m_leftMargin - 5, y, m_leftMargin, y);

        // 绘制刻度值
        painter.drawText(QRect(0, y - 10, m_leftMargin - 8, 20),
                         Qt::AlignRight | Qt::AlignVCenter,
                         QString::number(value));
    }

    painter.restore();
}

void BarChartWidget::drawBars(QPainter &painter)
{
    if (m_alarmCounts.isEmpty())
        return;

    painter.save();

    int chartWidth = width() - m_leftMargin - m_rightMargin;
    int chartBottom = height() - m_bottomMargin;
    int chartTop = m_topMargin;
    int chartHeight = chartBottom - chartTop;

    int maxValue = getMaxValue();
    if (maxValue == 0) maxValue = 1; // 避免除零

    int availableWidth = chartWidth - (m_alarmCounts.size() - 1) * m_barSpacing;
    m_barWidth = std::min(availableWidth / static_cast<int>(m_alarmCounts.size()), 30);

    for (int i = 0; i < m_alarmCounts.size(); i++) {
        int barHeight = (maxValue > 0) ? (m_alarmCounts[i] * chartHeight / maxValue) : 0;
        int x = m_leftMargin + i * (m_barWidth + m_barSpacing);
        int y = chartBottom - barHeight;

        // 绘制柱状图
        QRect barRect(x, y, m_barWidth, barHeight);
        painter.fillRect(barRect, m_barColors[i]);

        // 绘制边框
        //painter.setPen(Qt::black);
        //painter.drawRect(barRect);

        // 显示数值
        if (m_showValues && m_alarmCounts[i] > 0) {
            painter.setPen(Qt::black);
            QString valueText = QString::number(m_alarmCounts[i]);
            QRect textRect(x, y - 20, m_barWidth, 20);
            painter.drawText(textRect, Qt::AlignCenter, valueText);
        }
    }

    painter.restore();
}

void BarChartWidget::drawLabels(QPainter &painter)
{
    painter.save();

    int chartBottom = height() - m_bottomMargin;
    int chartWidth = width() - m_leftMargin - m_rightMargin;

    QFont font = painter.font();
    font.setPointSize(8);
    painter.setFont(font);
    painter.setPen(Qt::black);

    int availableWidth = chartWidth - (m_alarmCounts.size() - 1) * m_barSpacing;
    m_barWidth = std::min(availableWidth / static_cast<int>(m_alarmCounts.size()), 30);

    for (int i = 0; i < m_levelNames.size(); i++) {
        int x = m_leftMargin + i * (m_barWidth + m_barSpacing);
        QRect textRect(x, chartBottom + 5, m_barWidth, 20);

        // 如果文本太长，旋转显示
        QFontMetrics metrics(font);
        if (metrics.horizontalAdvance(m_levelNames[i]) > m_barWidth) {
            painter.save();
            painter.translate(x + m_barWidth / 2, chartBottom + 30);
            painter.rotate(45);
            painter.drawText(QRect(-50, 0, 100, 20), Qt::AlignCenter, m_levelNames[i]);
            painter.restore();
        } else {
            painter.drawText(textRect, Qt::AlignCenter, m_levelNames[i]);
        }
    }

    painter.restore();
}

int BarChartWidget::getMaxValue() const
{
    if (m_alarmCounts.isEmpty())
        return 0;

    return *std::max_element(m_alarmCounts.constBegin(), m_alarmCounts.constEnd());
}

QSize BarChartWidget::sizeHint() const
{
    return QSize(480, 280);
}

QSize BarChartWidget::minimumSizeHint() const
{
    return QSize(480, 300);
}
